package com.jzg.sys.common.shiro;

import com.jzg.sys.api.base.CacheService;
import com.jzg.sys.api.sec.ResourceService;
import com.jzg.sys.dao.entity.SecResource;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.config.Ini;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.*;

/**
 * @description:
 * @author:asxx 李志鹏
 * @create:2019-03-12 16:05
 */
@Component
@ConfigurationProperties(prefix="shiro")
public class ShiroUtil {
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private CacheService cacheService;
    //格式化数据，符合shiro的格式，如：perms["admin"]
    public static final String PREMISSION_FORMAT = "perms[\"{0}\"]";
    @Value("${cus.sysCode}")
    private String sysCode;
    private List<String> anon = new ArrayList<>();


    public Map<String, String> loadFilterChainDefinitions() {
        List<SecResource> resources = resourceService.getAll(sysCode);
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        anon.forEach(e->filterChainDefinitionMap.put(e,"anon"));
        for (SecResource resource : resources) {
            if (StringUtils.isEmpty(resource.getResourceContent())) {
                continue;
            }
            //如果资源的值为分号分隔，则循环构造元数据。分号分隔好处是对一批相同权限的资源，不需要逐个定义
            if (resource.getResourceContent().indexOf(";") != -1) {
                String[] sources = resource.getResourceContent().split(";");
                for (String source : sources) {
                    putDefinitionSection(filterChainDefinitionMap,source, resource.getResourceCode());
                }
            } else {
                putDefinitionSection(filterChainDefinitionMap,resource.getResourceContent(), resource.getResourceCode());
            }
        }
        filterChainDefinitionMap.put("/**", "statelessAuthc");

        return  filterChainDefinitionMap;
    }

    private void putDefinitionSection(Map<String, String> map, String key, String value) {
//		System.out.println("加载数据库权限：【key=" + key + "\tvalue=" + MessageFormat.format(PREMISSION_FORMAT, value) + "】");
        map.put(key,"statelessAuthc"+","+ MessageFormat.format(PREMISSION_FORMAT, value));
//	    section.put(key, MessageFormat.format(PREMISSION_FORMAT, value));
    }

    public List<String> getAnon() {
        return anon;
    }

    public void setAnon(List<String> anon) {
        this.anon = anon;
    }
}
